import {
    createSlice
} from '@reduxjs/toolkit'
import {
    USER_KEY
} from '../utils/constant'
import qiankunActions from '../utils/actions'
import {
    getUser
} from '../utils'
const {
    reducer: userReducer,
    actions
} = createSlice({
    name: USER_KEY,
    initialState: {
        user: getUser()
    },
    reducers: {
        // 登录和登出
        setUser(state, actions) {
            console.log('set user', actions.payload)
            state.user = actions.payload
            localStorage.setItem(USER_KEY, JSON.stringify(actions.payload))

            qiankunActions.setGlobalState({
                user: actions.payload
            })
        },
        removeUser(state) {
            console.log('remove user')
            state.user = null
            localStorage.removeItem(USER_KEY)
            setTimeout(()=>{
                qiankunActions.setGlobalState({
                    user: null
                })
            }, 0)
        }
    }
})


export const {
    setUser,
    removeUser,
    add
} = actions
export default userReducer